package com.baidu.track.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.platform.core.b.*;
import com.baidu.track.R;
import com.baidu.track.model.HistoryModel;
import com.baidu.track.model.StationModel;
import com.baidu.track.model.Url;
import com.baidu.track.model.item;
import com.baidu.track.utils.BitmapUtil;
import com.baidu.track.utils.HttpUtil;
import com.baidu.track.utils.Json2ModelUtil;
import com.baidu.track.utils.ViewUtil;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class MainActivity extends BaseActivity {

    private SDKReceiver mReceiver;

    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    MapView mMapView;
    BaiduMap mBaiduMap;

    private MyLocationData locData;

    String url= Url.follow;
    String url2= Url.history;
    String url3= Url.station;
    private item item;
    private HistoryModel historyModel;
    private HistoryModel historyModel2;
    private StationModel stationModel;
    //    显示信息窗
    private InfoWindow mInfoWindow;

    private boolean flag;
    ViewUtil viewUtil;
//    GeoCoder mGeCoder= GeoCoder.newInstance();
//    private String addr;
    /**
     * 构造广播监听类，监听 SDK key 验证以及网络异常广播
     */
    public class SDKReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {
            String s = intent.getAction();
            if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
                Toast.makeText(MainActivity.this,"apikey验证失败，地图功能无法正常使用",Toast.LENGTH_SHORT).show();
            } else if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK)) {
                Toast.makeText(MainActivity.this,"apikey验证成功",Toast.LENGTH_SHORT).show();
            } else if (s.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
                Toast.makeText(MainActivity.this,"网络错误",Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // apikey的授权需要一定的时间，在授权成功之前地图相关操作会出现异常；apikey授权成功后会发送广播通知，我们这里注册 SDK 广播监听者
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK);
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
        iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
        mReceiver = new SDKReceiver();
        registerReceiver(mReceiver, iFilter);
        BitmapUtil.init();
        viewUtil=new ViewUtil();
        init();

    }

    private void init() {
        //创建查询按钮
        Button trace = (Button) findViewById(R.id.btn_createfence);
        //围栏报警
        Button query = (Button) findViewById(R.id.btn_fencealarm);
        //位置状态
        Button requestLocButton = (Button) findViewById(R.id.button1);
        //历史轨迹
        Button hisory = (Button) findViewById(R.id.btn_history);
        //停留报表
        Button station = (Button) findViewById(R.id.btn_station);

        requestLocButton.setText("普通");

        initMap();

        trace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, CreateFenceActivity.class);
                startActivity(intent);
            }
        });

        query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,FenceAlarmActivity.class);
                startActivity(intent);
            }
        });

        hisory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(historyModel2.getDevices()==null){
                    viewUtil.showToast(MainActivity.this,"没有历史记录");
                }
                if(historyModel2!=null&&historyModel2.getDevices()!=null){
                    Intent intent = new Intent(MainActivity.this,HistoryStaActivity.class);
                    intent.putExtra("history", (Serializable) historyModel2);
                    intent.putExtra("map", 1);
                    startActivity(intent);
                }

            }
        });
        station.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(stationModel.getArr()==null){
                    viewUtil.showToast(MainActivity.this,"没有停留记录");
                }
                if(stationModel!=null&&stationModel.getArr()!=null){
                    Intent intent = new Intent(MainActivity.this,StationActivity.class);
                    intent.putExtra("station", stationModel);
                    startActivity(intent);
                }
            }
        });

    }
    private void query(){
        HttpUtil httpUtil = new HttpUtil(MainActivity.this);
        httpUtil.getinfo(url, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }
            @Override
            public void onResponse(String response, int id) {
                item= Json2ModelUtil.jsonToBean(response, item.class);
                flag=true;
            }
        });
    }
    private void query2(){
        HttpUtil httpUtil = new HttpUtil(this);
        httpUtil.getinfo(url2, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }
            @Override
            public void onResponse(String response, int id) {
                historyModel= Json2ModelUtil.jsonToBean(response, HistoryModel.class);
                historyModel2=historyModel;
            }
        });
    }
    private void query3(){
        HttpUtil httpUtil = new HttpUtil(this);
        httpUtil.getinfo(url3, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }
            @Override
            public void onResponse(String response, int id) {
                stationModel= Json2ModelUtil.jsonToBean(response, StationModel.class);
            }
        });
    }

    private void initMap(){
        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(18.0f);
        MapStatus mMapStatus;//地图当前状态
        MapStatusUpdate mMapStatusUpdate;//地图将要变化成的状态
        mMapStatus = new MapStatus.Builder().overlook(-45).build();
        mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        mBaiduMap.setMapStatus(mMapStatusUpdate);
        mBaiduMap.setMapStatus(msu);
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL,false,BitmapUtil.bmGeo,0xAAFFFF88,0xAA00FF00));
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                //点击地图某个位置获取经纬度latLng.latitude、latLng.longitude
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                //点击地图上的poi图标获取描述信息：mapPoi.getName()，经纬度：mapPoi.getPosition()
                return false;

            }
        });
        // 定位初始化
        myListener = new MyLocationListenner();
        mLocClient = new LocationClient(getApplication());
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedLocationDescribe(true);
        option.setOpenGps(true); // 打开gps
        option.setIsNeedAddress(true);
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(3000);
        //option.setNeedDeviceDirect(true);
        mLocClient.setLocOption(option);
        mLocClient.registerLocationListener(myListener);
        mLocClient.start();
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 适配android M，检查权限
        List<String> permissions = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && isNeedRequestPermissions(permissions)) {
            requestPermissions(permissions.toArray(new String[permissions.size()]), 0);
        }
        if (!mLocClient.isStarted()) {
            mLocClient.start();
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    private boolean isNeedRequestPermissions(List<String> permissions) {
        // 定位精确位置
        addPermission(permissions, Manifest.permission.ACCESS_FINE_LOCATION);
        // 存储权限
        addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        // 读取手机状态
        addPermission(permissions, Manifest.permission.READ_PHONE_STATE);
        return permissions.size() > 0;
    }

    private void addPermission(List<String> permissionsList, String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BitmapUtil.clear();
        unregisterReceiver(mReceiver);
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {
        @SuppressLint("ResourceAsColor")
        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            query();
            query2();
            query3();
            if(flag){
                mCurrentLat =Double.valueOf(item.getLat());
                mCurrentLon =Double.valueOf(item.getLng());
                LatLng latLng = new LatLng(Double.valueOf(item.getLat()), Double.valueOf(item.getLng()));
                String locationDescribe = location.getLocationDescribe();
//                OnGetGeoCoderResultListener getCoderListener = new OnGetGeoCoderResultListener() {
//                    @Override
//                    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
//
//                    }
//
//                    @Override
//                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
//                            if(reverseGeoCodeResult==null){
//
//                            }else{
//                                addr=reverseGeoCodeResult.getAddress();
//                            }
//                    }
//                };
//                ReverseGeoCodeOption reverseGeoCodeOption = new ReverseGeoCodeOption();
//                reverseGeoCodeOption.location(new LatLng(mCurrentLat,mCurrentLon));
//                mGeCoder.reverseGeoCode(reverseGeoCodeOption);
                location.setLatitude(mCurrentLat);
                location.setLongitude(mCurrentLon);
                TextView textView=(TextView)findViewById(R.id.textMain);
//                textView.setText(addr);
                LatLng point = new LatLng(mCurrentLat, mCurrentLon);
                Button button = new Button(getApplicationContext());
                button.setWidth(500);
                button.setBackgroundResource(R.drawable.mapbubble);
                StringBuilder sb = new StringBuilder();
                StringBuilder sb1 = new StringBuilder();
                StringBuilder sb2 = new StringBuilder();
                StringBuilder sb3 = new StringBuilder();
                sb.append(item.getPositionTime());
                sb1.append(item.getStm());
                sb2.append(item.getStatus());
                sb3.append(item.getSpeed());
                button.setText(sb.toString()+"\n"+"停留时长:"+sb1.toString()+"分钟"+"\n"+sb2.toString()+"\n"+"速度:"+sb3+"km/h");
                button.setTextColor(R.color.black);
                MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
                //改变地图状态
                mBaiduMap.setMapStatus(msu);
                mInfoWindow=new InfoWindow(button,point,-50);
                locData = new MyLocationData.Builder().accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(-1).latitude(mCurrentLat).longitude(mCurrentLon).build();
                mBaiduMap.setMyLocationData(locData);
                mBaiduMap.showInfoWindow(mInfoWindow);
            }


        }

    }

}
